﻿using System;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;

namespace rabbitmqdemo.Controllers
{
    public partial class RabbitmqTestController
    {
        private string channelName = "message";
        [HttpGet]
        [Route("redissend")]
        public Object RedisSend()
        {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("192.168.3.34:6379"))
            {
                ISubscriber sub = redis.GetSubscriber();

                for (int i = 0; i < 100; i++)
                {
                    sub.Publish(channelName, "aaa");
                }
            }

            return "发送消息";
        }

        /// <summary>
        /// 这个的问题是如果订阅者没有提前订阅好的话,消息是不会保存的,也就是生产者消息发送前,消费者必须准备好了
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("redisget")]
        public Object RedisGet()
        {
            using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("192.168.3.34:6379"))
            {
                ISubscriber sub = redis.GetSubscriber();
                sub.Subscribe(channelName, (channel, message) => {

                    //输出收到的消息
                    Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
                });
                Console.WriteLine("已订阅 messages");
                Console.ReadKey();
            }

            return "读取消息";
        }
    }
}